//
//  JDHomeTableViewController.swift
//  JDWeiBo
//                                     
//  Created by apple on 15/6/23.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class JDHomeTableViewController: JDBaseTableViewController, StatusCellDelegate {

    /// 表格绑定的微博数据数组
    var statusesList: [JDStatus]? {
        didSet {
            // 刷新表格
            tableView.reloadData()
            
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        vi?.setUpViewInfo("visitordiscover_feed_image_house", mess: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        // 没用用户登入就返回
        if !uerLog {
            return
        }
        
        setupNavigationBar()
        
        loadData()
        
        // 可重用Cell
        tableView.registerClass(JDStatusForwardCell.self, forCellReuseIdentifier: JDStatusForwardCellIdentifier)
        
        tableView.registerClass(JDStatusNormalCell.self, forCellReuseIdentifier: JDStatusNormalCellIdentifier)
        // 设置行高
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = 300
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 下拉的标志
        refreshControl = JDRefreshControl()
        
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    // 定义行高缓存 [statusId: 行高]
    lazy var rowHeightCache = [Int: CGFloat]()
    
    // 清空缓存
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        rowHeightCache.removeAll()
    }

    ///  加载微博数据
    func loadData() {
        
        // 开始刷新-不会触发监听方法，会显示刷新控件
        refreshControl?.beginRefreshing()
        
        // 下拉刷新记号，取到数组中第一条数据的id
        var since_id = statusesList?.first?.id ?? 0
        
        // 上拉刷新，取到数组中最后1条数据的 id
        var max_id = 0
        
        if pullRefreshFlag {
            since_id = 0
            max_id = statusesList?.last?.id ?? 0
        }
        
        JDStatus.loadStatus (since_id, max_id: max_id) { (statuses, error) -> () in
            
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                // 不要把错误的相信信息告诉用户，程序员应该多测试！
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            // 提示，后续会有下拉刷新，没有新微博的情况，不要抱错！
            if statuses == nil {
                print("没有数据")
                return
            }
            
            // 跟踪转发微博
            print("加载了 \(statuses?.count) 条微博")
            
            // 判断是否是下拉刷新，将新的数据，添加到原有数组的前面
            if since_id > 0 {
                self.statusesList = statuses! + self.statusesList!
            } else if max_id > 0 {
                // 上拉刷新
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = false
            } else {
                // 初始刷新
                self.statusesList = statuses
            }
        }

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        vi?.startAnmiation()
    }
    // 实例化
    var delegate = JDHomeFenLei()
    
    // title点击事件
    func titleButtonClick() {
        
        let sb = UIStoryboard(name: "JDFriendGroup", bundle: nil)
        
        let vc = sb.instantiateViewControllerWithIdentifier("JDFriendGroupSB")
        
        vc.transitioningDelegate = delegate
        
        // 设置自定义转场模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    ///  数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
//        cell.textLabel?.text = statusesList![indexPath.row].text
        // 数据模型
        let status = statusesList![indexPath.row]
        
        // 标示符
        let ID = JDStatusCell.cellIdentifier(status)
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! JDStatusCell
        
        cell.photoDelegate = self
        
        cell.status = status
        
        // 判断是否是最后一行
        if indexPath.row == statusesList!.count - 1 {
            pullRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    // Cell 的代理方法
    func statusCellDidSelectedPhoto(cell: JDStatusCell, photoIndex: Int) {
        if cell.status?.largePicURLs == nil {
            return
        }
        
        // 传递数据！- 图像的数组 & 用户选中的照片索引
        let vc = JDPhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 1. 取到对象
        let status = statusesList![indexPath.row]
        
        // 1.1 判断是否缓存了行高，如果有直接返回
        if rowHeightCache[status.id] != nil {
            return rowHeightCache[status.id]!
        }
        
        // 2. 获取 cell － 从可重用的 缓冲池 中提取一个cell，说明之前用过，要计算行高准确，需要实例化一个cell
        // 2.1 取可重用的 ID
        let ID = JDStatusCell.cellIdentifier(status)
        // 2.2 定义一个类，默认是原创微博的 cell
        var cls: AnyClass = JDStatusNormalCell.self
        // 2.3 根据 ID 判断是否是转发微博
        if ID == JDStatusForwardCellIdentifier {
            cls = JDStatusForwardCell.self
        }
        // 2.4 根据 cls 创建 cell
        let cell = cls.new() as! JDStatusCell
        
        // 3. 返回行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
    }
    
    private func setupNavigationBar() {
        
        // 判断用户是否登入
        // 如果用户是空 就返回
        if sharedUserAccount == nil {
            return
        }
        
        // 设置按钮
        let leftBtn = UIButton()
        
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        let rightBtn = UIButton()
        
        rightBtn.frame = CGRectMake(0, 0, 30, 30)
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        // 设置标题
        
        let name = sharedUserAccount!.name!
        
        let titleButton = JDHomeTitleButton()
        titleButton.frame = CGRectMake(0, 0, 120, 30)
        titleButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        titleButton.titleLabel?.font = UIFont.systemFontOfSize(17.0)
        titleButton.setTitle(name + "  ", forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        
        titleButton.addTarget(self, action: "titleButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    /// 上拉刷新标记
    private var pullRefreshFlag = false
    
    private var isPresented = false
}
